package com.hyh.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyh.ad.common.utils.SecurityUtils;
import com.hyh.admin.domain.resources.DTO.WordCountDto;
import com.hyh.admin.domain.resources.Resources;
import com.hyh.admin.domain.resources.ResourcesCategory;
import com.hyh.admin.domain.resources.ResourcesComment;
import com.hyh.admin.domain.resources.vo.ResourcesCategoryVo;
import com.hyh.admin.mapper.resources.ResourcesCategoryMapper;
import com.hyh.admin.mapper.resources.ResourcesMapper;
import com.hyh.admin.service.IResourcesCategoryService;
import com.hyh.admin.service.IResourcesCollectService;
import com.hyh.admin.service.IResourcesService;
import com.hyh.admin.service.IResourcesViewsService;
import com.hyh.admin.tool.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/*
 * 资源列表实现类
 */
@Service
public class ResourcesServiceImpl implements IResourcesService {

    @Autowired
    private ResourcesMapper resourcesMapper;

    @Autowired
    private IResourcesCollectService resourceCollectService;

    @Autowired
    private IResourcesViewsService resourcesViewsService;

    @Autowired
    private ResourcesCategoryMapper resourcesCategoryMapper;

    @Autowired
    private FileUploadService fileUploadService;

    @Value("${file.upload-dir}") // 从配置文件获取上传目录
    private String uploadDir;


    @Override
    public List<Resources> selectResourcesComment(Resources resources) {
        LambdaQueryWrapper<Resources> queryWrapper = new LambdaQueryWrapper<>(resources);
        return resourcesMapper.selectList(queryWrapper);
    }

    @Override
    public int updateResources(Resources resources) {
        return resourcesMapper.updateById(resources);
    }

    @Override
    public int deleteResources(Resources resources) {
        return resourcesMapper.deleteById(resources);
    }

    @Override
    public int insertResources(Resources resources) {
        return resourcesMapper.insert(resources);
    }

    @Override
    public List<Resources> selectResourcesByUserId(Long userId) {
        LambdaQueryWrapper<Resources> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Resources::getUserId, userId);
        queryWrapper.eq(Resources::getStatus, 1);
        return resourcesMapper.selectList(queryWrapper);
    }

    @Override
    public Resources selectResourcesById(Long id) {
        return resourcesMapper.selectById(id);
    }

    @Override
    public int deleteResourcesBatch(Long[] ids) {
        return resourcesMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public List<Resources> selectResourcesByHot(Resources resources) {
        LambdaQueryWrapper<Resources> queryWrapper = new LambdaQueryWrapper<>(resources);
        queryWrapper.orderByDesc(Resources::getHotDegree);
        queryWrapper.eq(Resources::getStatus, 1);
        return resourcesMapper.selectList(queryWrapper);
    }

    @Override
    public List<ResourcesCategoryVo> selectResourcesByCategoryId(Long categoryId) {
        return resourcesMapper.selectResourcesByCategoryId(categoryId);
    }

    @Override
    public List<ResourcesCategoryVo> selectResourcesList() {
        return resourcesMapper.selectResourcesList();
    }

    @Override
    public List<Resources> selectResourcesByParentId(Long parentId) {
        LambdaQueryWrapper<Resources> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Resources::getParentId, parentId);
        queryWrapper.eq(Resources::getStatus, 1);
        return resourcesMapper.selectList(queryWrapper);
    }

    @Override
    public Resources saveResource(Long parentId, String title, String description, Long categoryId, String tags, MultipartFile coverImage, MultipartFile video) {
        try {
            // 1️⃣ 上传封面图片
            String coverImagePath = fileUploadService.saveFile(coverImage, "images");

            // 2️⃣ 上传视频
            String videoPath = fileUploadService.saveFile(video, "videos");

            // 3️⃣ 保存到数据库
            Resources resource = new Resources();
            resource.setTitle(title);
            resource.setDescription(description);
            resource.setCategoryId(categoryId);
            resource.setTags(tags);
            resource.setCoverImage(coverImagePath);
            resource.setUrl(videoPath);
            resource.setUserId(SecurityUtils.getLoginUser().getUser().getId());
            if (parentId != null) {
                resource.setParentId(parentId);
            }

            return resourcesMapper.insert(resource) > 0 ? resource : null;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败：" + e.getMessage(), e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Resources> selectResourcesByIds(String[] ids) {
        List<Long> longIds = Arrays.stream(ids)
                .map(Long::valueOf) // 转换 String -> Long
                .collect(Collectors.toList());
        //
        //// 查询数据库
        //List<Resources> resources = resourcesMapper.selectBatchIds(longIds);
        //
        //// **按传入 ID 顺序排序**
        //Map<Long, Resources> resourceMap = resources.stream()
        //        .collect(Collectors.toMap(Resources::getId, r -> r));
        //
        //return longIds.stream()
        //        .map(resourceMap::get)
        //        .filter(Objects::nonNull) // 避免空值
        //        .collect(Collectors.toList());
        return resourcesMapper.selectByIds(longIds);
    }

    @Override
    public List<Resources> selectResourcesListPage(Resources resources) {
        LambdaQueryWrapper<Resources> queryWrapper = new LambdaQueryWrapper<>(resources);
        return resourcesMapper.selectList(queryWrapper);
    }

    @Override
    public int updateStatus(Long id, String status) {
        LambdaQueryWrapper<Resources> queryWrapper = new LambdaQueryWrapper<>();
        Resources resources = resourcesMapper.selectById(id);
        resources.setStatus(status);
        return resourcesMapper.updateById(resources);
    }

    @Override
    public List<WordCountDto> selectResourcesWordList(Resources resources) {
        Long userId = SecurityUtils.getLoginUser().getUser().getId();
        List<Resources> collectList = resourceCollectService.selectResourcesCollect(userId);
        List<Resources> viewList = resourcesViewsService.selectResourcesViewsByUserId(userId);
        // 合并两个列表
        List<Resources> allResources = new ArrayList<>();
        allResources.addAll(collectList);
        allResources.addAll(viewList);

        // 词频统计
        Map<String, Integer> tagCountMap = new HashMap<>();

        for (Resources res : allResources) {
            String tags = res.getTags();
            if (tags != null && !tags.isEmpty()) {
                String[] tagArray = tags.split(",");
                for (String tag : tagArray) {
                    tag = tag.trim(); // 去除空格
                    if (!tag.isEmpty()) {
                        tagCountMap.put(tag, tagCountMap.getOrDefault(tag, 0) + 1);
                    }
                }
            }
        }
        List<WordCountDto> wordCountList = new ArrayList<>();

        for (Map.Entry<String, Integer> entry : tagCountMap.entrySet()) {
            WordCountDto wordCountDto = new WordCountDto(entry.getKey(), entry.getValue());
            wordCountList.add(wordCountDto);
        }


        return wordCountList;
    }

    @Override
    public List<WordCountDto> selectResourcesLearnList(Resources resources) {
        Long userId = SecurityUtils.getLoginUser().getUser().getId();
        List<Resources> collectList = resourceCollectService.selectResourcesCollect(userId);
        List<Resources> viewList = resourcesViewsService.selectResourcesViewsByUserId(userId);
        // 合并两个列表
        List<Resources> allResources = new ArrayList<>();
        allResources.addAll(collectList);
        allResources.addAll(viewList);

        // 词频统计
        Map<String, Integer> tagCountMap = new HashMap<>();

        for (Resources res : allResources) {
            Long categoryId = res.getCategoryId();
            if (categoryId != null) {
                String categoryName = resourcesCategoryMapper.selectById(categoryId).getName();
                tagCountMap.put(categoryName, tagCountMap.getOrDefault(categoryName, 0) + 1);
            }

        }
        List<WordCountDto> wordCountList = new ArrayList<>();

        for (Map.Entry<String, Integer> entry : tagCountMap.entrySet()) {
            WordCountDto wordCountDto = new WordCountDto(entry.getKey(), entry.getValue());
            wordCountList.add(wordCountDto);
        }
        return wordCountList;
    }
}

